import { permissionUtils, tokenUtils } from '@gyk/gyk-utils'
import { defineStore } from 'pinia'
import { permissionState } from '../types'
import STORE_NAMES from '../store-names'
import router, { constantRoutes, dynamicRoutes } from '@gyk/gyk-router'
import { InnerLink, ParentView } from '@gyk/gyk-ui'
import useStore from '../index'
import { menuService } from '@gyk/gyk-api'

const usePermissionStore = defineStore(STORE_NAMES.PERMISSION, {
  state: (): permissionState => {
    return {
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: [],
      parentId: tokenUtils.getSystemId(),
      Layout: {},
    }
  },
  getters: {

  },
  actions: {
    // 生成路由
    GenerateRoutes(): Promise<any> {
      return new Promise<any>(resolve => {
        // 向后端请求路由数据
        menuService.getRouters({ parentId: this.parentId }).then(res => {
          const sdata = JSON.parse(JSON.stringify(res.data))
          const rdata = JSON.parse(JSON.stringify(res.data))
          const sidebarRoutes = this.filterAsyncRouter(sdata)
          const rewriteRoutes = this.filterAsyncRouter(rdata, false, true)
          const asyncRoutes = this.filterDynamicRoutes(dynamicRoutes);
          const firstPath = rewriteRoutes[0]?.path + '/' + rewriteRoutes[0]?.children[0]?.path
          // 默认将第一个路由添加为index路由
          rewriteRoutes.push({ path: '/index', redirect: firstPath, hidden: true })
          rewriteRoutes.push({ path: '/:pathMatch(.*)', redirect: '/404', hidden: true })
          console.log(rewriteRoutes)
          asyncRoutes.forEach(item => {
            router.addRoute(item);
          })
          // 获取第一个菜单
          const firstMenu = rewriteRoutes[0]
          router.push({ path: firstMenu.path })

          this.routes = rewriteRoutes
          this.sidebarRouters = constantRoutes.concat(sidebarRoutes)
          this.defaultRoutes = sidebarRoutes
          this.topbarRouters = sidebarRoutes
          resolve(rewriteRoutes)
        })
      })
    },
    // 遍历后台传来的路由字符串
    filterAsyncRouter(asyncRouterMap: any, lastRouter: any = false, type: any = false) {
      return asyncRouterMap.filter(route => {
        if (type && route.children) {
          route.children = this.filterChildren(route.children)
        }
        if (route.component) {
          // Layout ParentView 组件特殊处理
          if (route.component === 'Layout') {
            route.component = this.Layout
          } else if (route.component === 'ParentView') {
            route.component = ParentView
          } else if (route.component === 'InnerLink') {
            route.component = InnerLink
          } else {
            route.component = this.loadView(route.component)
          }
        }
        if (route.children != null && route.children && route.children.length) {
          route.children = this.filterAsyncRouter(route.children, route, type)
        } else {
          delete route['children']
          delete route['redirect']
        }
        return true
      })
    },
    filterChildren(childrenMap: any, lastRouter: any = false) {
      let children: any[] = []
      childrenMap.forEach((el, index) => {
        if (el.children && el.children.length) {
          if (el.component === 'ParentView' && !lastRouter) {
            el.children.forEach(c => {
              c.path = el.path + '/' + c.path
              if (c.children && c.children.length) {
                children = children.concat(this.filterChildren(c.children, c))
                return
              }
              children.push(c)
            })
            return
          }
        }
        if (lastRouter) {
          el.path = lastRouter.path + '/' + el.path
        }
        children = children.concat(el)
      })
      return children
    },
    // 动态路由遍历，验证是否具备权限
    filterDynamicRoutes(routes: any[]) {
      const res: any[] = []
      routes.forEach(route => {
        const store = useStore()
        const user = store.user
        if (route.permissions) {
          if (permissionUtils.hasPermiOr(user.permissions, route.permissions)) {
            res.push(route)
          }
        } else if (route.roles) {
          if (permissionUtils.hasRoleOr(user.roles, route.roles)) {
            res.push(route)
          }
        }
      })
      return res
    },
    loadView(view: any) {
      const viteComponents = import.meta.glob("@/**/*.vue")
      const path = "/src/pages/" + view + '.vue'
      return viteComponents[path]
    }
  }
});


export default usePermissionStore